<template>
  <div class="app-container">
    <div class="action-container">
      <el-button @click="handleCreateClueEvent">增加<i class="el-icon--right" /></el-button>
      <el-button type="primary" @click.prevent="handleImportClueEvent()">导入<i class="el-icon--right" /></el-button>
      <el-button @click.prevent="downloadTemplate()">下载模板<i class="el-icon--right"></i></el-button>
    </div>
    <div class="filter-container">
      <el-input v-model="listQuery.f_lk_serial" style="width: 200px;" class="filter-item" placeholder="线索编码" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.f_lk_respondent" style="width: 200px; margin-left: 10px;" class="filter-item" placeholder="被反映人" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.f_eq_superviseOrg$parentId" style="width: 150px; margin-left: 10px;" class="filter-item" placeholder="办理机关一级" @change='onOrgList1Changed'>
        <el-option label="全部(一级机关）" value="" />
        <el-option v-for="item in orgList1" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
      <el-select v-model="listQuery.f_eq_superviseOrgId" style="width: 150px; margin-left: 10px;" class="filter-item" placeholder="办理机关二级" @change="handleFilter">
        <el-option label="全部(二级机关）" value="" />
        <el-option v-for="item in orgList2" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
      <el-select v-model="listQuery.f_eq_status" style="width: 120px; margin-left: 10px;" class="filter-item" placeholder="状态" @change="handleFilter">
        <el-option label="全部" value="" />
        <el-option label="未处理" value="0" />
        <el-option label="已处置" value="1" />
        <el-option label="已办结" value="2" />
      </el-select>
      <el-button class="filter-item" type="success" icon="el-icon-search" @click="resetFiler">重置</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
    </div>

    <el-table v-loading.body="listLoading" :data="list" element-loading-text="数据正在加载中，请稍后..." border fit highlight-current-row>
      <el-table-column align="center" label="ID" width="50">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="线索编码">
        <template slot-scope="scope">
          <el-link type="primary" @click="handleShowWorkflowDialogEvent(scope.row)">{{ scope.row.serial }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="被反映人">
        <template slot-scope="scope">
          {{ scope.row.respondent }}
        </template>
      </el-table-column>
      <el-table-column label="办理机关一级" width="210">
        <template slot-scope="scope">
          {{ ((scope.row.superviseOrg || {}).parent || {}).name }}
        </template>
      </el-table-column>
      <el-table-column label="办理机关二级" width="210">
        <template slot-scope="scope">
          {{ (scope.row.superviseOrg || {}).name }}
        </template>
      </el-table-column>
      <el-table-column label="受理时间">
        <template slot-scope="scope">
          {{ scope.row.receiptTime }}
        </template>
      </el-table-column>
      <el-table-column label="处置时间">
        <template slot-scope="scope">
          {{ scope.row.disposalTime }}
        </template>
      </el-table-column>
      <el-table-column label="处置方式">
        <template slot-scope="scope">
          {{ scope.row.disposalWay | disposalValueFilter }}
        </template>
      </el-table-column>
      <el-table-column label="办结时间">
        <template slot-scope="scope">
          {{ scope.row.closureTime }}
        </template>
      </el-table-column>
      <el-table-column label="办理结果">
        <template slot-scope="scope">
          {{ scope.row.conclusion | conclusionValueFilter }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusClassFilter">{{ scope.row.status | statusValueFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="145">
        <template slot-scope="scope">
          <el-button type="" size="small" @click="handleUpdateClueEvent(scope.row)">修改</el-button>
          <el-button type="danger" size="small" @click="handleDeleteClueEvent(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination
        background
        :current-page.sync="listQuery.page"
        :page-sizes="[10,20,30,50]"
        :page-size="listQuery.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 增加/修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="clue" label-position="left" label-width="150px" style="width: 400px; margin-left:50px;">
        <el-form-item label="ID" prop="id">
          <span>{{ clue.id }}</span>
        </el-form-item>
        <el-form-item label="线索编码" prop="serial">
          <el-input v-model="clue.serial" />
        </el-form-item>
        <el-form-item label="被反映人" prop="respondent">
          <el-input v-model="clue.respondent" />
        </el-form-item>
        <el-form-item label="办理机关一级" prop="parentOrgId">
          <el-select v-model="clue.parentOrgId" @change='onOrgList1ChangedInDialog'>
            <el-option v-for="item in orgList1" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="办理机关二级" prop="superviseOrgId">
          <el-select v-model="clue.superviseOrgId">
            <el-option v-for="item in orgList2InDialog" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="受理时间" prop="receiptTime">
          <el-date-picker v-model="clue.receiptTime" type="date" placeholder="受理时间" />
        </el-form-item>
        <el-form-item label="处置时间" prop="disposalTime">
          <el-date-picker v-model="clue.disposalTime" type="date" placeholder="处置时间" />
        </el-form-item>
        <el-form-item label="处置方式" prop="disposalWay">
          <el-select v-model="clue.disposalWay">
            <el-option label="请选择" :value="0" />
            <el-option label="初步核实" :value="1" />
            <el-option label="谈话函询" :value="2" />
            <el-option label="了结" :value="3" />
            <el-option label="暂存" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="办结时间" prop="closureTime">
          <el-date-picker v-model="clue.closureTime" type="date" placeholder="办结时间" />
        </el-form-item>
        <el-form-item label="办理结果" prop="conclusion">
          <el-select v-model="clue.conclusion">
            <el-option label="请选择" :value="0" />
            <el-option label="立案" :value="1" />
            <el-option label="了结" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="tryCreateClue">确定</el-button>
        <el-button v-else type="primary" @click="tryUpdateClue">确定</el-button>
      </div>
    </el-dialog>

    <!--导入对话框-->
    <el-dialog title="导入节目" :visible.sync="showImportClueDialog" width="40%">
      <el-form ref="importClueForm" :model="clueFile" label-position="left" label-width="100px" style="width: 600px; margin-left:50px;">
        <el-form-item label="上传文件" prop="title">
          <el-upload ref="upload" :action="importClueUrl" :auto-upload="false" :limit="1" accept=".xls;.xlsx" :on-exceed="exceedFileListSize">
            <el-button slot="trigger" size="small" type="primary">选取Excel文件</el-button>
            <div class="el-upload__tip">xlsx文件, 1M以内，格式见模板下载</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showImportClueDialog = false">取消</el-button>
        <el-button type="primary" @click="tryImportClueFile">确定</el-button>
      </div>
    </el-dialog>

    <!--导入结果对话框-->
    <el-dialog title="导入结果" :visible.sync="showImportResultDialog">
      <el-table :data="importResult.data" border fit highlight-current-row>
        <el-table-column label="线索编码" width="300" align="left">
          <template slot-scope="scope">
            {{ (scope.row.value||{}).serial }}
          </template>
        </el-table-column>
        <el-table-column label="结果" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.result | resultClassFilter">{{ scope.row.result }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="left">
          <template slot-scope="scope">
            {{ scope.row.message }}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleCloseImportResultEvent">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="流程图" :visible.sync="showWorkflowDialog" width="900px">
      <ClueWorkflow :clue="workflow"> </ClueWorkflow>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleCloseWorkflowDialogEvent">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import store from '@/store'
import { MessageBox } from 'element-ui'
import { createClue, updateClue, deleteClue, getClueList } from '@/api/clue'
import { getOrgList } from '@/api/org'
import { getDateString } from '@/utils'
import { getToken } from '@/utils/auth'
import { parseErrorMessage } from '@/utils/request'
import ClueWorkflow from './components/ClueWorkflow'

export default {
  components: { ClueWorkflow },
  filters: {
    statusClassFilter(status) {
      const statusMap = {
        0: 'danger',
        1: 'warning',
        2: 'success'
      }
      return statusMap[status]
    },
    statusValueFilter(status) {
      const statusMap = {
        0: '未处理',
        1: '已处置',
        2: '已办结'
      }
      return statusMap[status]
    },
    resultClassFilter(status) {
      const classMap = {
        '成功': 'success',
        '失败': 'danger'
      }
      return classMap[status]
    },
    disposalValueFilter(value) {
      const map = {
        1: '初步核实',
        2: '谈话函询',
        3: '了结',
        4: '暂存'
      }
      return map[value]
    },
    conclusionValueFilter(value) {
      const map = {
        1: '立案',
        2: '了结'
      }
      return map[value]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      total: null,
      listQuery: {
        page: 1,
        size: 20,
        f_lk_serial: undefined,
        f_lk_respondent: undefined,
        f_eq_superviseOrg$parentId: '',
        f_eq_superviseOrgId: '',
        f_eq_status: undefined
      },
      orgList1: [],
      orgList2: [],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        create: '增加',
        update: '修改'
      },
      rules: {
        serial: [{ required: true, message: '线索编码不能为空。', trigger: 'change' }],
        respondent: [{ required: true, message: '被反映人不能为空。', trigger: 'change' }],
        parentOrgId: [{ required: true, message: '办理机关一级不能为空。', trigger: 'change' }],
        superviseOrgId: [{ required: true, message: '办理机关二级不能为空。', trigger: 'change' }],
        receiptTime: [{ required: true, message: '受理时间不能为空。', trigger: 'change' }]/*,
        disposalTime: [{ required: true, message: '处置时间不能为空。', trigger: 'change' }],
        disposalWay: [{ required: true, message: '处置方式不能为空。', trigger: 'change' }],
        closureTime: [{ required: true, message: '办结时间不能为空。', trigger: 'change' }],
        conclusion: [{ required: true, message: '办理结果不能为空。', trigger: 'change' }]*/
      },
      clue: {
        id: undefined,
        serial: undefined,
        respondent: undefined,
        parentOrgId: undefined,
        superviseOrgId: undefined,
        receiptTime: undefined,
        disposalTime: undefined,
        disposalWay: undefined,
        closureTime: undefined,
        conclusion: undefined
      },
      orgList2InDialog: [],
      showImportClueDialog: false,
      importClueUrl: process.env.VUE_APP_BASE_API + '/api/flow/clues/import',
      clueFile: {},
      showImportResultDialog: false,
      importResult: {},
      showWorkflowDialog: false,
      workflow: {
      }
    }
  },
  created() {
    // 查询数据
    this.fetchData()
    //查询一级部门
    this.fetchOrgList1()
  },
  methods: {
    fetchOrgList1() {
      getOrgList({ f_eq_type: 1 }).then(response => {
        this.orgList1 = response.data
      })
    },
    fetchOrgList2(parentId) {
      getOrgList({ f_eq_parentId: parentId }).then(response => {
        this.orgList2 = response.data
      })
    },
    onOrgList1Changed() {
      if (this.listQuery.f_eq_superviseOrg$parentId !== '') {
        this.fetchOrgList2(this.listQuery.f_eq_superviseOrg$parentId)
      } else {
        this.orgList2 = []
      }
      // 一级部门改变后，默认二级部门默认全选
      this.listQuery.f_eq_superviseOrgId = ''
      this.listQuery.page = 1
      this.fetchData()
    },
    fetchData() {
      this.listLoading = true
      getClueList(this.listQuery).then(response => {
        this.listLoading = false
        this.list = response.data
        this.total = response.total
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    resetFiler() {
      this.listQuery.f_lk_serial = undefined
      this.listQuery.f_lk_respondent = undefined
      this.listQuery.f_eq_superviseOrg$parentId = ''
      this.listQuery.f_eq_superviseOrgId = ''
      this.listQuery.f_eq_status = undefined
      this.listQuery.page = 1
      this.listQuery.size = 20
      this.fetchData()
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },
    onOrgList1ChangedInDialog() {
      getOrgList({ f_eq_parentId: this.clue.parentOrgId }).then(response => {
        this.orgList2InDialog = response.data
        if (this.orgList2InDialog && this.orgList2InDialog.length > 0) {
          this.clue.superviseOrgId = this.orgList2InDialog[0].id
        }
      })
    },
    handleCreateClueEvent() {
      this.clue.id = 0
      this.clue.receiptTime = getDateString()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    tryCreateClue() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const clue = Object.assign({}, this.clue)
          // 过滤掉办理机关一级
          delete clue.parentOrgId
          createClue(clue).then(() => {
            this.dialogFormVisible = false
            this.$notify({ title: '成功', message: '创建成功', type: 'success', duration: 2000 })
            this.fetchData()
          })
        }
      })
    },
    handleUpdateClueEvent(row) {
      const t = Object.assign({}, row) // copy obj
      this.clue.id = t.id
      this.clue.serial = t.serial
      this.clue.respondent = t.respondent
      this.clue.parentOrgId = (t.superviseOrg || {}).parentId || 0
      this.clue.superviseOrgId = t.superviseOrgId
      this.clue.receiptTime = t.receiptTime
      this.clue.disposalTime = t.disposalTime
      this.clue.disposalWay = t.disposalWay
      this.clue.closureTime = t.closureTime
      this.clue.conclusion = t.conclusion

      // 根据一级部门，更新二级部门列表
      getOrgList({ f_eq_parentId: this.clue.parentOrgId }).then(response => {
        this.orgList2InDialog = response.data
      })

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    tryUpdateClue() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const clue = Object.assign({}, this.clue)
          delete clue.parentOrgId
          updateClue(clue).then(() => {
            this.dialogFormVisible = false
            this.$notify({ title: '成功', message: '更新成功', type: 'success', duration: 2000 })
            this.fetchData()
          })
        }
      })
    },
    handleDeleteClueEvent(id) {
      MessageBox.confirm('请确认是否要删除该记录？', '操作确认', { confirmButtonText: '是', cancelButtonText: '否', type: 'warning' })
        .then(() => {
          deleteClue(id).then(() => {
            this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
            this.fetchData()
          })
        }, () => {
        })
    },
    handleImportClueEvent() {
      this.showImportClueDialog = true
      this.$nextTick(() => {
        this.$refs['importClueForm'].clearValidate()
      })
    },
    exceedFileListSize(files, fileList) {
      fileList.pop()
      fileList.push(files[0])
    },
    tryImportClueFile() {
      // 此处仍使用validate机制，是为了以后对其他字段进行输入校验
      this.$refs['importClueForm'].validate((valid) => {
        if (valid) {
          if (this.$refs.upload.uploadFiles.length === 0) {
            this.$message.error('请选择Excel(*xls;*.xlsx)文件')
            return
          }

          const files = this.$refs.upload.uploadFiles
          for (const file of files) {
            const name = file.name.toLowerCase()
            if (!name.endsWith('.xls') && !name.endsWith('.xlsx')) {
              this.$message.error('文件格式错误，请上传xlxs文件')
              return
            }

            // 文件大小不超过10M
            if (file.size > 10485760) {
              this.$message.error('文件太大，请上传10M以内的文件')
              return
            }
          }

          // 自动从form中获取提交的字段（包括上传文件）
          const form = new FormData(this.$refs.importClueForm.$el) // 文件对象

          // XMLHttpRequest 对象
          const xhr = new XMLHttpRequest()
          xhr.open('post', this.importClueUrl, true)

          // 加入Token做鉴权，此处使用XMLHttpRequest方式，就是为了在header中能够携带token
          xhr.setRequestHeader('Authorization', getToken())

          const $this = this
          xhr.onload = function() {
            if (xhr.status === 401) {
              store.dispatch('FedLogOut').then(() => {
                location.reload()// 为了重新实例化vue-router对象 避免bug
              })
            } else if (xhr.status < 200 || xhr.status >= 300) {
              const error = parseErrorMessage(xhr.responseText)
              $this.$message.error(error || '上传文件失败')
            } else {
              $this.$refs.upload.clearFiles()
              $this.showImportClueDialog = false
              $this.showImportResultDialog = true
              $this.importResult = JSON.parse(xhr.responseText)
            }
          }

          xhr.onerror = function(xhr, e) {
            $this.$message.error('上传文件失败')
          }

          // 发送请求
          xhr.send(form)
        }
      })
    },
    handleCloseImportResultEvent() {
      this.showImportResultDialog = false
      this.fetchData()
    },
    handleShowWorkflowDialogEvent(row) {
      this.workflow = row
      this.showWorkflowDialog = true
    },
    handleCloseWorkflowDialogEvent() {
      this.showWorkflowDialog = false
    },
    downloadTemplate() {
      axios.get(process.env.VUE_APP_BASE_API + '/api/flow/clues/import/template', { responseType: 'blob', headers: { Authorization: getToken() }})
        .then(({ data }) => {
          // console.log(data)
          const blob = new Blob([data], { type: 'application/octet-stream' })
          const link = document.createElement('a')
          link.href = URL.createObjectURL(blob)
          link.setAttribute('download', '线索信息导入模板.xls')
          link.click()
        }).catch(error => {
        if (error.response.status === 401) {
          store.dispatch('FedLogOut').then(() => {
            location.reload()// 为了重新实例化vue-router对象 避免bug
          })
        }
      })
    }
  }
}
</script>
